<template>
  <div class="modern-container">
    <!-- 搜索区域 -->
    <el-card v-show="showSearch" class="search-card" shadow="hover">
      <div class="search-container">
        <el-row :gutter="10">
          <el-col :span="22">
            <el-input
              v-model="queryParams.account"
              class="search-input"
              clearable
              placeholder="搜索账号"
              prefix-icon="el-icon-search"
              size="mini"
              @keyup.enter.native="handleQuery"/>
          </el-col>
          <el-col :span="2">
            <el-button
              icon="el-icon-search"
              size="mini"
              type="primary"
              @click="handleQuery">搜索
            </el-button>
          </el-col>
        </el-row>
      </div>
    </el-card>

    <!-- 操作按钮区 -->
    <el-card class="action-card" shadow="hover">
      <div class="action-container">
        <div class="left-actions">
          <el-button
            v-hasPermi="['game:account:add']"
            icon="el-icon-plus"
            plain
            size="mini"
            type="primary"
            @click="handleAdd">新增
          </el-button>
          <el-button
            v-hasPermi="['game:account:remove']"
            :disabled="multiple"
            icon="el-icon-delete"
            plain
            size="mini"
            type="danger"
            @click="handleDelete">删除
          </el-button>
          <el-button
            v-hasPermi="['game:account:export']"
            icon="el-icon-download"
            plain
            size="mini"
            type="warning"
            @click="handleExport">导出
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card" shadow="hover">
      <div class="table-container">
        <el-table
          v-loading="loading"
          :data="accountList"
          :header-cell-style="{background:'rgba(250,252,255,0.8)', color:'#606266'}"
          :row-class-name="getRowClassName"
          class="status-table"
          height="100%"
          @selection-change="handleSelectionChange">
          <el-table-column align="center" type="selection" width="55"/>
          <el-table-column align="center" label="账号" min-width="120" prop="account"/>
          <el-table-column align="center" label="密码" min-width="120" prop="password"/>
          <el-table-column align="center" label="备注" min-width="120" prop="remark" show-overflow-tooltip/>
          <el-table-column align="center" label="创建时间" min-width="160" prop="createTime">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" fixed="right" label="操作" width="180">
            <template slot-scope="scope">
              <el-button
                v-hasPermi="['game:account:edit']"
                icon="el-icon-edit"
                size="mini"
                type="text"
                @click="handleUpdate(scope.row)"
              >修改
              </el-button>
              <el-button
                v-hasPermi="['game:account:edit']"
                icon="el-icon-edit"
                size="mini"
                type="text"
                @click="handlePreview(scope.row)">配置
              </el-button>
              <el-button
                v-hasPermi="['game:account:remove']"
                icon="el-icon-delete"
                size="mini"
                type="text"
                @click="handleDelete(scope.row)"
              >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-container">
          <pagination
            v-show="total>0"
            :limit.sync="queryParams.pageSize"
            :page.sync="queryParams.pageNum"
            :total="total"
            size="mini"
            @pagination="getList"
          />
        </div>
      </div>
    </el-card>
    <!-- 预览对话框 -->
    <el-dialog :show-close="false" :visible.sync="previewVisible" append-to-body center title="配置预览" width="400px">
      <template-preview :preview-data="previewData"/>
      <div slot="footer" class="dialog-footer">
        <el-row :gutter="10">
          <el-col :span="12">
            <el-button size="mini" style="width: 100%" @click="cancel">取 消</el-button>
          </el-col>
          <el-col :span="12">
            <el-button size="mini" style="width: 100%" type="primary" @click="submitPreview">保 存</el-button>
          </el-col>
        </el-row>

      </div>
    </el-dialog>
    <!-- 添加或修改游戏账号对话框 -->
    <el-dialog :title="title" :visible.sync="open" append-to-body class="custom-dialog" width="400px">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" size="mini">
        <el-form-item v-if="!form.id" label="游戏" prop="gameId">
          <el-row :gutter="10">
            <el-col :span="21">
              <el-select v-model="form.gameId" placeholder="请选择游戏" style="width: 100%">
                <el-option
                  v-for="item in gameList"
                  :key="item.id"
                  :label="item.gameName"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-col>
            <el-col :span="2">
              <el-button :icon="gameLoading ? 'el-icon-loading':'el-icon-refresh'" circle size="mini"
                         @click="getGameList"/>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="账号" prop="account">
          <el-input v-model="form.account" placeholder="请输入账号" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" placeholder="请输入密码" show-password/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-row :gutter="10">
          <el-col :span="12">
            <el-button size="mini" style="width: 100%" @click="cancel">取 消</el-button>
          </el-col>
          <el-col :span="12">
            <el-button size="mini" style="width: 100%" type="primary" @click="submitForm">确 定</el-button>
          </el-col>
        </el-row>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {addAccount, delAccount, getAccount, listAccount, updateAccount} from "@/api/game/account";
import {updateTemplate} from "@/api/template/account";
import {listGame} from "@/api/game/game";
import {parseTime} from "@/utils/ruoyi";
import TemplatePreview from "@/layout/components/Template/TemplatePreview.vue";

export default {
  name: "Account",
  components: {TemplatePreview},
  data() {
    return {
      // 遮罩层
      loading: true,
      gameLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 游戏账号表格数据
      accountList: [],
      gameList: [],// 预览相关
      previewVisible: false,
      previewData: {
        templateName: '',
        templateConfig: []
      },
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        agentId: null,
        templateId: null,
        account: null,
        password: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        gameId: [
          {required: true, message: "请选择游戏"},
        ],
        account: [
          {required: true, message: "请输入账号"},
          {min: 6, max: 20, message: '账号长度必须介于 6 和 20 之间', trigger: 'blur'}
        ],
        password: [
          {required: true, message: "请输入密码"},
          {min: 6, max: 32, message: '密码长度必须介于 6 和 32 之间', trigger: 'blur'}
        ]

      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    parseTime,
    /** 获取行的类名，用于设置状态颜色 */
    getRowClassName({row}) {
      // 根据状态返回不同的类名
      switch (row.status) {
        case 0:
          return 'status-pending';
        case 1:
          return 'status-processing';
        case 2:
          return 'status-cooling';
        case 3:
          return 'status-error';
        case 4:
          return 'status-disabled';
        default:
          return '';
      }
    },
    /** 查询游戏账号列表 */
    getList() {
      this.loading = true;
      this.getGameList();
      listAccount(this.queryParams).then(response => {
        this.accountList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询游戏列表 */
    getGameList() {
      this.gameLoading = true;
      listGame(this.queryParams).then(response => {
        this.gameList = response.rows;
        this.gameLoading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.previewVisible = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        userId: null,
        agentId: null,
        templateId: null,
        account: null,
        password: null,
        status: null,
        delFlag: null,
        createTime: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加游戏账号";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getAccount(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改游戏账号";
      });
    },
    // 预览按钮操作
    handlePreview(row) {
      this.reset();
      const id = row.id
      getAccount(id).then(response => {
        this.form = response.data;
        if (response.data && response.data.accountTemplate) {
          this.previewData = {
            templateName: response.data.accountTemplate.templateName,
            templateConfig: response.data.accountTemplate.templateConfig
          };
          this.previewVisible = true;
        } else {
          this.$modal.msgError("该账号没有模板");
        }

      });
    },
    /** 提交预览 */
    submitPreview() {
      console.log(this.form.accountTemplate)
      if (!this.form.accountTemplate) {
        this.$modal.msgError("保存异常");
        return;
      }

      updateTemplate(this.form.accountTemplate).then(res => {
        this.$modal.msgSuccess("保存成功");
        this.previewVisible = false;
        this.getList();
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateAccount(this.form).then(res => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addAccount(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除游戏账号编号为"' + ids + '"的数据项？').then(function() {
        return delAccount(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('game/account/export', {
        ...this.queryParams
      }, `account_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style scoped>
.modern-container {
  padding: 16px;
  background-color: #f5f7fa;
  height: calc(100vh - 100px);
  display: flex;
  flex-direction: column;
  gap: 16px;
}

::v-deep .el-dialog__body {
  padding: 0;
}

::v-deep .el-dialog__header {
  font-weight: bold;
  font-size: 14px;
  letter-spacing: 3px;
}
/* 卡片样式 */
.search-card,
.action-card,
.table-card {
  border-radius: 8px;
  margin-bottom: 0;
  transition: all 0.3s;
  border: none;
}

.table-card {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.search-card:hover,
.action-card:hover,
.table-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.search-card ::v-deep .el-card__body,
.action-card ::v-deep .el-card__body {
  padding: 16px;
}

.table-card ::v-deep .el-card__body {
  padding: 0;
  height: 100%;
  display: flex;
  flex-direction: column;
}

/* 表格容器 */
.table-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
}

/* 搜索区域样式 */
.search-container {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 12px;
}

.search-input {
  width: 240px;
}

.search-buttons {
  display: flex;
  gap: 8px;
}

@media screen and (max-width: 768px) {
  .search-container {
    flex-direction: column;
    align-items: flex-start;
  }

  .search-input {
    width: 100%;
  }

  .search-buttons {
    width: 100%;
  }
}

/* 操作按钮区域 */
.action-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 12px;
}

.left-actions {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

@media screen and (max-width: 768px) {
  .action-container {
    flex-direction: column;
    align-items: flex-start;
  }

  .left-actions {
    margin-bottom: 12px;
  }
}

/* 表格样式 */
.status-table {
  width: 100%;
  border-radius: 8px 8px 0 0;
  overflow: hidden;
  flex: 1;
}

.status-table ::v-deep .el-table__header-wrapper th {
  background-color: rgba(250, 252, 255, 0.8) !important;
  color: #606266;
  font-weight: 500;
  padding: 8px 0;
}

.status-table ::v-deep .el-table__row {
  transition: all 0.3s;
}

.status-table ::v-deep .el-table__row:hover {
  background-color: #f5f7fa;
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

/* 状态颜色定义 */
.status-table ::v-deep .status-pending {
  border-left: 3px solid #409EFF; /* 待处理 - 蓝色 */
}

.status-table ::v-deep .status-processing {
  border-left: 3px solid #E6A23C; /* 处理中 - 黄色 */
}

.status-table ::v-deep .status-cooling {
  border-left: 3px solid #67C23A; /* 冷却中 - 绿色 */
}

.status-table ::v-deep .status-error {
  border-left: 3px solid #F56C6C; /* 异常 - 红色 */
}

.status-table ::v-deep .status-disabled {
  border-left: 3px solid #909399; /* 停用 - 灰色 */
  opacity: 0.8;
}

/* 分页容器 */
.pagination-container {
  display: flex;
  justify-content: flex-end;
  background-color: white;
  border-radius: 0 0 8px 8px;
  margin-top: 0 !important;
  padding: 5px !important;
}

/* 对话框样式 */
.custom-dialog ::v-deep .el-dialog {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.custom-dialog ::v-deep .el-dialog__header {
  padding: 16px 20px;
  background: #f5f7fa;
  border-bottom: 1px solid #ebeef5;
}

.custom-dialog ::v-deep .el-dialog__title {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

.custom-dialog ::v-deep .el-dialog__body {
  padding: 20px;
}

.custom-dialog ::v-deep .el-dialog__footer {
  padding: 12px 20px;
  border-top: 1px solid #ebeef5;
  background: #f5f7fa;
}

.custom-dialog ::v-deep .el-form-item__label {
  font-weight: 500;
  font-size: 13px;
}

.custom-dialog ::v-deep .el-input__inner,
.custom-dialog ::v-deep .el-textarea__inner {
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  transition: all 0.3s;
}

.custom-dialog ::v-deep .el-input__inner:focus,
.custom-dialog ::v-deep .el-textarea__inner:focus {
  border-color: #409EFF;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

/* 响应式调整 */
@media screen and (max-width: 576px) {
  .modern-container {
    padding: 12px;
    gap: 12px;
  }

  .search-card ::v-deep .el-card__body,
  .action-card ::v-deep .el-card__body,
  .pagination-container {
    padding: 12px;
  }

  .custom-dialog ::v-deep .el-dialog {
    width: 90% !important;
    margin: 5vh auto !important;
  }

  .custom-dialog ::v-deep .el-dialog__body {
    padding: 16px;
  }
}

/* 修复el-table在flex布局中的高度问题 */
.status-table ::v-deep .el-table__inner-wrapper {
  height: 100%;
}

.status-table ::v-deep .el-table__body-wrapper {
  overflow-y: auto;
}
</style>
